package cn.deschen.eshop.auth.controller;

import cn.deschen.eshop.auth.enums.ValidateCodeTypeEnum;
import cn.deschen.eshop.auth.properties.DefaultSecurityConstants;
import cn.deschen.eshop.auth.validate.ValidateCodeProcessorHolder;
import cn.deschen.eshop.common.enums.GlobalEnum;
import cn.deschen.eshop.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author hanbin_chen
 * @Description 验证码应用层
 * @DateTime 2021/1/15 14:43
 * @Version V1.0.0
 */
@RestController
@Slf4j
public class ValidateCodeController {

    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    /**
     * 生成验证码接口
     * @param request
     * @param response
     * @param type
     * @throws Exception
     */
    @GetMapping(DefaultSecurityConstants.DEFAULT_PREFIX_GENERATE_URL_CODE + "/{type}")
    public void createCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type)
            throws Exception {
        ValidateCodeTypeEnum codeTypeEnum = ValidateCodeTypeEnum.codeTypeEnum(type);
        // 判断该类型是否存在
        if (null == codeTypeEnum) {
            log.error("【权限模块】{} 类型不存在", type);
            throw new GlobalException(GlobalEnum.EXIST_ERROR, type + "类型不存在");
        }

        validateCodeProcessorHolder.getValidateCodeProcessor(type).createCode(
                new ServletWebRequest(request, response), codeTypeEnum);
    }
}
